package com.example.dictionary.service;

import com.example.dictionary.config.DictionaryProperties;
import com.example.dictionary.repository.DictionarySourceMapper;
import com.example.dictionary.repository.DownloadTaskMapper;
import com.example.dictionary.repository.WordEntryMapper;
import com.example.memento.model.DictionarySource;
import com.example.memento.model.DownloadTask;
import com.example.memento.model.WordEntry;
import com.example.memento.model.DictionaryStats;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 词典服务 - 整合下载和解析功能
 */
@Service
public class DictionaryService {
    
    private static final Logger log = LoggerFactory.getLogger(DictionaryService.class);
    
    private final DictionaryDownloadService downloadService;
    private final DictionaryParseService parseService;
    private final WordEntryMapper wordEntryMapper;
    private final DictionarySourceMapper dictionarySourceMapper;
    private final DownloadTaskMapper downloadTaskMapper;
    private final DictionaryProperties properties;
    
    public DictionaryService(DictionaryDownloadService downloadService, 
                           DictionaryParseService parseService,
                           WordEntryMapper wordEntryMapper,
                           DictionarySourceMapper dictionarySourceMapper,
                           DownloadTaskMapper downloadTaskMapper,
                           DictionaryProperties properties) {
        this.downloadService = downloadService;
        this.parseService = parseService;
        this.wordEntryMapper = wordEntryMapper;
        this.dictionarySourceMapper = dictionarySourceMapper;
        this.downloadTaskMapper = downloadTaskMapper;
        this.properties = properties;
    }
    
    /**
     * 加载所有启用的词典源
     */
    @Async
    public CompletableFuture<Void> loadAllDictionaries() {
        return downloadService.downloadAllEnabledSources()
                .thenCompose(downloadTasks -> {
                    List<CompletableFuture<Void>> parseFutures = downloadTasks.stream()
                            .filter(task -> task.getStatus() == DownloadTask.TaskStatus.COMPLETED)
                            .map(this::loadDictionaryFromTask)
                            .toList();
                    
                    return CompletableFuture.allOf(parseFutures.toArray(new CompletableFuture[0]));
                });
    }
    
    /**
     * 从下载任务加载词典
     */
    @Async
    public CompletableFuture<Void> loadDictionaryFromTask(DownloadTask task) {
        return CompletableFuture.runAsync(() -> {
            try {
                Path filePath = Path.of(task.getLocalPath());
                String sourceName = task.getSourceName();
                
                // 查找对应的词典源配置
                DictionarySource source = properties.getSources().stream()
                        .filter(s -> s.getName().equals(sourceName))
                        .findFirst()
                        .orElseThrow(() -> new RuntimeException("找不到词典源配置: " + sourceName));
                
                // 解析文件
                List<WordEntry> entries = parseService.parseFile(filePath, sourceName, source.getFormat()).get();
                
                // 保存到数据库
                saveEntries(entries);
                
                log.info("词典加载完成: {} 条目数: {}", sourceName, entries.size());
                
            } catch (Exception e) {
                log.error("加载词典失败: {}", task.getSourceName(), e);
                throw new RuntimeException("词典加载失败", e);
            }
        });
    }
    
    /**
     * 批量保存词典条目
     */
    @Transactional
    public void saveEntries(List<WordEntry> entries) {
        int batchSize = properties.getParsing().getBatchSize();
        
        for (int i = 0; i < entries.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, entries.size());
            List<WordEntry> batch = entries.subList(i, endIndex);
            
            // 使用MyBatis-Flex批量插入
            for (WordEntry entry : batch) {
                // 设置创建时间戳
                entry.onCreate();
                wordEntryMapper.insert(entry);
            }
            log.debug("保存批次: {}-{} / {}", i, endIndex, entries.size());
        }
    }
    
    /**
     * 搜索单词
     */
    public List<WordEntry> searchWord(String word) {
        return wordEntryMapper.findByWord(word);
    }
    
    /**
     * 模糊搜索单词
     */
    public List<WordEntry> searchWordContaining(String keyword) {
        return wordEntryMapper.findByWordLike(keyword);
    }
    
    /**
     * 根据源搜索
     */
    public List<WordEntry> searchBySource(String source) {
        return wordEntryMapper.findBySource(source);
    }
    
    /**
     * 获取词典统计信息
     */
    public DictionaryStats getStatistics() {
        DictionaryStats stats = new DictionaryStats();
        stats.setTotalWords(wordEntryMapper.countAll());
        
        // 获取按来源统计的词条数
        List<Object> sourceCounts = wordEntryMapper.countBySource();
        // 这里需要将结果转换为Map，具体实现根据实际需要调整
        
        return stats;
    }
}
